﻿// <copyright file="MainWindow.xaml.cs" company="Pelican Design &amp; Development">
//      Copyright (c) Pelican Design &amp; Development. All Rights Reserved.
// </copyright>

namespace AppDomains
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Security;
    using System.Windows;

    /// <summary>
    /// Main application window running in limited-permission AppDomain.
    /// </summary>
    [SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Controls events are explicit enough to be documented.")]
    [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Controls events are explicit enough to be documented.")]
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void buttonSaveFile_Click(object sender, RoutedEventArgs e)
        {
            DataTools.WriteFileForMe("MainUIFromWindow.txt", "Hello from main UI." + Environment.NewLine + "I'm saving this through DataTools, because it has more privileges than me.");
            MessageBox.Show("Success: file saved.");
        }

        private void buttonFailSavingFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data\MainUIOwnFromWindow.txt"), "Hello from main UI." + Environment.NewLine + "I will fail trying to save file myself, because I don't have enough privileges.");
                Console.WriteLine("\tWhat? There is a huge problem: the sandboxed code had just accessed a file.");
            }
            catch (SecurityException ex)
            {
                if (ex.PermissionType.FullName == "System.Security.Permissions.FileIOPermission")
                {
                    Console.WriteLine("\tOk. It failed as expected. Great!");
                    MessageBox.Show("Success: failed to save, as expected.");
                }
                else
                {
                    throw;
                }
            }
        }
    }
}
